package com.gz.jdbc.datasource;

import com.mchange.v2.c3p0.ComboPooledDataSource;
import org.junit.jupiter.api.Test;

import java.beans.PropertyVetoException;
import java.io.FileInputStream;
import java.io.IOException;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Properties;
@SuppressWarnings("all")
public class c3p0 {

    @Test
    //方式一
    public void testc3p0_1() throws IOException, PropertyVetoException, SQLException {
        //1.创建一个数据源对象
        ComboPooledDataSource comboPooledDataSource = new ComboPooledDataSource();
        //2.通过配置文件mysql.properties 获取相关信息
        Properties properties = new Properties();
        properties.load(new FileInputStream("src\\mysql.properties"));
        //读取相关的属性值
        String url = properties.getProperty("url");
        String user = properties.getProperty("user");
        String password = properties.getProperty("password");
        String driver = properties.getProperty("driver");

        //给数据源 comboPooledDataSource 设置相关参数
        //注意: 连接管理是由 comboPooledDataSource 来管理
        comboPooledDataSource.setDriverClass(driver);
        comboPooledDataSource.setJdbcUrl(url);
        comboPooledDataSource.setUser(user);
        comboPooledDataSource.setPassword(password);

        //设置初始化连接数
        comboPooledDataSource.setInitialPoolSize(10);//连接池初始大小为10(即可以有10个连接)
        //最大连接数
        comboPooledDataSource.setMinPoolSize(50);

        //测试连接池效率，测试对mysql 5000000次操作
        long start = System.currentTimeMillis();
        for (int i = 0; i < 5000000; i++) {
            Connection connection = comboPooledDataSource.getConnection();//核心方法
//            System.out.println("连接成功");
            connection.close();
        }
        long end = System.currentTimeMillis();
        System.out.println("c3p0 连接5000000次musql耗时: "+(end - start)); //6637ms
    }

    //第二种方式 使用配置文件模版来完成
    //1.将c3p0提供的c3p0.config.xml拷贝到src目录下
    //2.该文件指定了数据库与连接池的相关参数
    @Test
    //方式二，方式一种的参数都写在配置文件c3p0-config.xml中，更方便,本质相同，所以消耗时间差不多
    public void testc3p0_2() throws SQLException {
        ComboPooledDataSource comboPooledDataSource = new ComboPooledDataSource("gz");
        long start = System.currentTimeMillis();
        for (int i = 0; i < 5000000; i++) {
            Connection connection = comboPooledDataSource.getConnection();//核心方法
//            System.out.println("连接成功");
            connection.close();
        }
        long end = System.currentTimeMillis();
        System.out.println("c3p0 连接5000000次musql耗时: "+(end - start)); //7169ms
    }

}
